﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Registration_User : System.Web.UI.Page
{

    //ToDo: pass out year addition 
    //ToDo: department addition 

    Notes.NotesDB _objNotesDB = new Notes.NotesDB();
    RegistrationData reg = new RegistrationData();
    RegexValidator rv = new RegexValidator();
    DataSet ds = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["User"] != null)
            {
                Response.Redirect(Common.LoggedPage);
            }
            else
            {
                BindUniversity();
                BusinessLogic busin = new BusinessLogic();
                busin.checkcookies_ForLogin(Request.Url.ToString());
            }
        }
        else
        {
            if (!(String.IsNullOrEmpty(txtPassword.Text.Trim())))
            {
                txtPassword.Attributes["value"] = txtPassword.Text;
            }
            if (!(String.IsNullOrEmpty(txtCPass.Text.Trim())))
            {
                txtCPass.Attributes["value"] = txtCPass.Text;
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        ds = new DataSet();
        if (ValidatePage())
        {
            string salt = string.Empty;
            salt = reg.RandomString(5);
            reg.FirstName = txtFirstName.Value;
            reg.LastName = txtLastName.Value;
            reg.UserName = txtUsername.Value;
            reg.Email = txtEmail.Value;
            reg.Password = reg.protectpassword(reg.protectpassword(txtPassword.Text) + salt);
            reg.UnivID = Convert.ToInt16(ddlUniversity.SelectedValue);
            reg.CollegeID = Convert.ToInt32(ddlCollege.SelectedValue);
            reg.otherCollegeName = txtCollege.Text;
            reg.MobileNo = Convert.ToInt64(txtMobile.Text);
            reg.IsMobileDisclosed = chkDisclose.Checked;
            reg.Salt = salt;
            ds = reg.InsertRegistrationDetails();
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = ds.Tables[0].Rows[0];

                    EmailData.UserName = txtUsername.Value;
                    EmailData.Name = txtFirstName.Value;

                    string strConfig = string.Empty;
                    strConfig = EmailData.WebsiteLink;
                    string Link = strConfig + "Reg-ActivateAccount.aspx?id=";
                    string strCode = DateTime.Now.ToString("MM/dd/yyyyhh:mm:ss:fff");
                    strCode = rv.RemoveSpecialChar1(strCode);
                    strCode = strCode + "-" + Convert.ToString(dr["UserID"]);
                    Link = Link + strCode;
                    reg.Update_EmailVerificationLink(Convert.ToInt32(dr["UserID"]), Link);
                    string subject = EmailData.WebsiteAdmin + " - Activate Account";
                    EmailData.Link = Link;
                    try
                    {
                        SendEmails auto = new SendEmails();
                        auto.GeneralEmail(subject, txtEmail.Value, 1);
                        lblError.Text = "Thanks for registration with us. We have sent you an email please verify your email.";
                    }
                    catch (Exception ex)
                    {
                        lblError.Text = ex.Message;
                    }
                    reset();
                }
                else lblError.Text = "Some Error has occured, please try again.";
            }
            else lblError.Text = "Some Error has occured, please try again.";
        }
    }

    protected void BindUniversity()
    {
        IDataReader dr;
        ddlUniversity.Items.Clear();
        ListItem lst1 = new ListItem();
        lst1.Text = "Select";
        lst1.Value = "0";
        ddlUniversity.Items.Add(lst1);
        dr = _objNotesDB.Select_Universities();
        if (dr != null)
        {
            while (dr.Read())
            {
                ListItem lst = new ListItem();
                lst.Text = dr["UniversityName"].ToString();
                lst.Value = dr["UniversityID"].ToString();
                ddlUniversity.Items.Add(lst);
            }
        }
        dr.Close();

        ListItem _objList = new ListItem();
        _objList.Text = "Other";
        _objList.Value = "-1";
        ddlUniversity.Items.Add(_objList);
    }

    protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCollege();
    }

    protected void BindCollege()
    {
        int UnivId = 0;
        IDataReader dr;
        ddlCollege.Items.Clear();
        ListItem lst1 = new ListItem();
        lst1.Text = "Select";
        lst1.Value = "0";
        ddlCollege.Items.Add(lst1);
        if (ddlUniversity.SelectedValue == "-1")
        {
            divOtherCollege.Style.Value = "display:block";
            divCollege.Visible = false;
        }
        else
        {
            divOtherCollege.Style.Value = "display:none";
            divCollege.Visible = true;
        }
        if (ddlUniversity.SelectedItem.Text != "Select" && ddlUniversity.SelectedValue != "-1")
        {
            UnivId = Convert.ToInt32(ddlUniversity.SelectedValue.ToString());
        }
        else
        {
            UnivId = 0;
        }
        if (UnivId > 0)
        {
            dr = _objNotesDB.Select_College(UnivId);
            if (dr != null)
            {
                while (dr.Read())
                {
                    ListItem lst = new ListItem();
                    lst.Text = dr["CollegeName"].ToString();
                    lst.Value = dr["CollegeID"].ToString();
                    ddlCollege.Items.Add(lst);
                }

            }
            dr.Close();

            ListItem _objList = new ListItem();
            _objList.Text = "Other";
            _objList.Value = "-1";
            ddlCollege.Items.Add(_objList);
        }
    }

    #region for Validation

    protected bool ValidatePage()
    {
        bool IsValidated = true;
        if (MandatoryFieldsCheck())
        {
            if (!PatternCheck())
            {
                IsValidated = false;
            }
        }
        else
        {
            IsValidated = false;
        }
        return IsValidated;
    }

    protected bool MandatoryFieldsCheck()
    {

        if (txtFirstName.Value == string.Empty)
        {
            lblError.Text = "Required field - First Name";
            return false;
        } 
        if (txtEmail.Value == string.Empty)
        {
            lblError.Text = "Required field - Email";
            return false;
        }
        if (txtUsername.Value == string.Empty)
        {
            lblError.Text = "Required field - User Name";
            return false;
        }

        if (txtPassword.Text == string.Empty)
        {
            lblError.Text = "Required field - Password";
            return false;
        }
        if (txtCPass.Text == string.Empty)
        {
            lblError.Text = "Required field - Confirm Password";
            return false;
        }

        if (txtPassword.Text != txtCPass.Text)
        {
            lblError.Text = "Password and confirm password do not match.";
            return false;
        }
        if (txtMobile.Text == string.Empty)
        {
            lblError.Text = "Required field - Mobile No";
            return false;
        }
        if (ddlUniversity.SelectedValue == "-1" || ddlCollege.SelectedValue == "-1")
        {
            if (txtCollege.Text == string.Empty)
            {
                lblError.Text = "Please enter the college name.";
                return false;
            }
        }
        else
        {
            if (ddlUniversity.SelectedValue == "0")
            {
                lblError.Text = "Required field - University";
                return false;
            }
            if (ddlCollege.SelectedValue == "0")
            {
                lblError.Text = "Required field - College";
                return false;
            }
        }
        return true;
    }

    protected bool PatternCheck()
    {
        lblError.Text = string.Empty;

        if (!rv.IsAlpha(txtFirstName.Value.Trim()))
        {
            lblError.Text = "First Name can contain alphabets only";
            return false;
        }
        if (!rv.IsAlpha(txtLastName.Value.Trim()))
        {
            lblError.Text = "Last Name can contain alphabets only";
            return false;
        }
        if (!rv.IsAlphaNumeric(txtUsername.Value.Trim()))
        {
            lblError.Text = "User Name can contain number or alphabets only";
            return false;
        }
        if (!rv.IsRegularExpression_Email(txtEmail.Value.Trim()))
        {
            lblError.Text = "E-MailID should be in correct format";
            return false;
        }
        if (!rv.IsValidMobileNumber(txtMobile.Text.Trim()))
        {
            lblError.Text = "Please enter a valid mobile number.";
            return false;
        }

        if (txtPassword.Text != txtCPass.Text)
        {
            lblError.Text = "Password do not match";
        }
        Validations vald = new Validations();
        if (Convert.ToBoolean(vald.CheckUserName(txtUsername.Value)))
        {
            lblError.Text = "This User Name already exists if you have forgotten the password you can try <a href='/Reg-Forgot-Password.aspx' class='whitelink fbox'>Reset Password</a>";
            return false;
        }
        if (Convert.ToBoolean(vald.CheckEmail(txtEmail.Value)))
        {
            lblError.Text = "This Email already exists  if you have forgotten the password you can try <a href='/Reg-Forgot-Password.aspx' class='whitelink fbox'>Reset Password</a>";
            return false;
        }
        if (vald.CheckMobileNo(Convert.ToInt64(txtMobile.Text)))
        {
            lblError.Text = "This Mobile No already exists  if you have forgotten the password you can try <a href='/Reg-Forgot-Password.aspx' class='whitelink fbox'>Reset Password</a>";
            return false;
        } 
        return true;
    }

    void reset()
    {
        txtFirstName.Value = string.Empty;
        txtLastName.Value = string.Empty;
        txtEmail.Value = string.Empty;
        txtUsername.Value = string.Empty;
        txtPassword.Attributes["value"] = string.Empty;
        txtCPass.Attributes["value"] = string.Empty;
        ddlUniversity.SelectedValue = "0";
        ddlCollege.SelectedValue = "0";
        txtMobile.Text = string.Empty;
        txtCollege.Text = string.Empty;
        divOtherCollege.Style.Value = "display:none";
    }

    #endregion

    protected void ddlCollege_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlCollege.SelectedValue == "-1")
            divOtherCollege.Style.Value = "display:block";
        else
            divOtherCollege.Style.Value = "display:none";
    }
}